import time
import logging

import uuid

from django.core.exceptions import ValidationError

from trade.models.member_goods import MemberGoods
from .models import Members
from libs.common import rand_str, get_ip, is_empty_str, success, error
from libs.auth import jwt_encode, generate_password, check_post_request
from libs.form import RawJsonForm

logger = logging.getLogger(__name__)


def sign_up(request):
    now = int(time.time())
    form = RawJsonForm(request.body)
    username = form.get('username')
    passwd = form.get('passwd')
    if is_empty_str(passwd):
        return error('密码不能为空')

    member = Members()
    salt = rand_str(8, 1)
    member.sn = str(uuid.uuid5(uuid.NAMESPACE_DNS, 'ns.member' + salt))
    member.username = username
    member.password = generate_password(passwd, salt)
    member.salt = salt
    member.avatar = ''
    member.ip = get_ip(request)
    member.created = now
    member.updated = now

    try:
        member.full_clean()
        member.save()
    except ValidationError as e:
        return error(';'.join(e.messages))
    except Exception as ex:
        msg = ''
        if str(ex).index('(1062,') == 0:
            msg = '用户已存在'
        return error(msg)
    else:
        token = jwt_encode(member.id)
        data = {"token": token}
        return success(data)


def sign_in(request):
    form = RawJsonForm(request.body)
    username = form.get('username')
    if is_empty_str(username):
        return error('用户名不能为空')
    passwd = form.get('passwd')
    if is_empty_str(passwd):
        return error('密码不能为空')
    try:
        member = Members.objects.get(username=username)
    except Members.DoesNotExist:
        return error('账号不存在')
    crypt_passwd = member.password
    if crypt_passwd != generate_password(passwd, member.salt):
        return error('密码错误')

    member.updated = int(time.time())
    try:
        member.save(update_fields=['updated'])
        token = jwt_encode(member.id)
    except Exception as ex:
        print(ex)
        logger.error(ex)
        return error('登录失败请重试')

    data = {
        'token': token,
        'username': member.username,
        'amount': member.amount,
        'frozen_funds': member.frozen_funds,
    }
    return success(data)


def get_member(member_id, *field):
    err = None
    try:
        member = Members.objects.values(*field).get(id=member_id)
    except Members.DoesNotExist:
        err = '账号不存在'
    return member, err


def my_goods_list(request):
    return_code, return_content = check_post_request(request)
    if return_code != 0:
        return return_content
    member_id = return_content
    goods_list = MemberGoods.objects.filter(member_id=member_id).order_by('-updated').all().values()
    return success(list(goods_list))
